package com.jade.store.wechat.biz.business.auth;

import com.alibaba.fastjson.JSON;
import com.jade.framework.base.context.ApplicationContextUtils;
import com.jade.framework.cache.CacheService;
import com.jade.store.wechat.biz.common.Configure;
import com.jade.store.wechat.biz.common.Log;
import com.jade.store.wechat.biz.common.Util;
import com.jade.store.wechat.biz.common.WxConstantUtil;
import com.jade.store.wechat.biz.protocol.auth.ComponentAccessTokenReq;
import com.jade.store.wechat.biz.protocol.auth.ComponentAccessTokenRes;
import com.jade.store.wechat.biz.protocol.three.Oauth2ComponentReq;
import com.jade.store.wechat.biz.protocol.three.Oauth2ComponentRes;
import com.jade.store.wechat.biz.service.auth.Oauth2ComponentService;
import com.jade.store.wechat.biz.service.menu.MenuCreateService;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;

/**
 * Created with IntelliJ IDEA.
 * User: jinya
 * Date: 2016/12/14
 * Time: 19:38
 * TEL :17701640710   MAIL:2009_jinya@163.com
 * To change this template use File | Settings | File Templates.
 */
public class Oauth2ComponentBusiness {

    //打log用
    private static Log log = new Log(LoggerFactory.getLogger(Oauth2ComponentBusiness.class));
    //执行结果
    private static String result = "";

    public Oauth2ComponentBusiness(String appid) throws IllegalAccessException, ClassNotFoundException, InstantiationException {

    }
    private CacheService cacheService = ApplicationContextUtils.getBean("system_cacheService");
    /**
     * 调用退款业务逻辑
     * @param req 这个数据对象里面包含了API要求提交的各种数据字段
     * @throws Exception
     */
    public Oauth2ComponentRes run(Oauth2ComponentReq req) throws Exception {
        ComponentAccessTokenReq reqcom=new ComponentAccessTokenReq();
        reqcom.setComponent_appid(Configure.appID);
        reqcom.setComponent_appsecret(Configure.appSecret);
        reqcom.setComponent_verify_ticket(getTicket());
        String responseString = sendJsonPost("https://api.weixin.qq.com/cgi-bin/component/api_component_token",reqcom);
        ComponentAccessTokenRes rescom = (ComponentAccessTokenRes) Util.getObjectFromJson(responseString, ComponentAccessTokenRes.class);
        req.setComponent_access_token(rescom.getComponent_access_token());
        req.setComponent_appid(Configure.appID);
        String resStr;
        long costTimeStart = System.currentTimeMillis();
        log.i("退款查询API返回的数据如下：");

        //将从API返回的XML数据映射到Java对象
        String reqUrl = String.format("https://api.weixin.qq.com/sns/oauth2/component/access_token?appid=%s&code=%s&grant_type=%s&component_appid=%s&component_access_token=%s",
                req.getAppid(), req.getCode(), req.getGrant_type(), req.getComponent_appid(), req.getComponent_access_token());
        Oauth2ComponentRes res = (Oauth2ComponentRes) Util.getObjectFromJson(sendJsonPost(reqUrl,req), Oauth2ComponentRes.class);
        return res;
    }
    private String getTicket(){
        String result="";
        Object obj=cacheService.get(WxConstantUtil.cache_component_verify_ticket);
        if(obj!=null){
            result=obj.toString();
        }
        return result;
    }
    /**
     * 通过Https�?API post xml数据
     *
     * @param url    API地址
     * @param xmlObj 要提交的XML数据对象
     * @return API回包的实际数�?
     * @throws IOException
     * @throws KeyStoreException
     * @throws UnrecoverableKeyException
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */

    public String sendJsonPost(String url, Object xmlObj) throws IOException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException {
        String postDataXML = JSON.toJSONString(xmlObj);
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();

            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            byte[] requestStringBytes = postDataXML.getBytes("UTF-8");

            conn.setRequestProperty("Content-length", "" + requestStringBytes.length);
            conn.setRequestProperty("Content-Type", "application/octet-stream");
            conn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
            conn.setRequestProperty("Charset", "UTF-8");

            OutputStream outputStream = conn.getOutputStream();
            outputStream.write(requestStringBytes);
            outputStream.flush();
            outputStream.close();

            //定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }
    public String getResult() {
        return result;
    }
}
